package com.licq.ldoc.writer.impl;

import com.licq.ldoc.domain.Element;
import com.licq.ldoc.utils.LowAgieUtils;
import com.licq.ldoc.writer.ElementWriter;
import com.licq.ldoc.writer.TableMetadata;
import com.licq.ldoc.writer.visitor.structure.StructureVisitor;
import com.lowagie.text.BadElementException;
import com.lowagie.text.Cell;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Table;

public class StructureWriter implements ElementWriter, TableMetadata {

	@Override
	public void write(Element element, Document document) throws DocumentException {
		document.add(writeStructure(element));
	}

	private Table writeStructure(com.licq.ldoc.domain.Element element)
			throws BadElementException, DocumentException {
		Table table = createStructureTable();
		writeStructureHeader(table, element);
		writeStructureSubHeader(table);
		writeStructureData(table, element);
		table.complete();
		return table;
	}
	
	private Table createStructureTable() throws BadElementException {
		Table table = new Table(TABLE_HEADERS.length);
		table.setWidth(90);
		table.setPadding(4f);
		table.setWidths(TABLE_WIDTHS);
		return table;
	}

    private void writeStructureData(Table table, com.licq.ldoc.domain.Element element) 
    	throws BadElementException {
        element.accept(new StructureVisitor(table));
    }

    private void writeStructureSubHeader(Table table) throws BadElementException {
    	for (String header : TABLE_HEADERS) {
    		table.addCell(LowAgieUtils.createTableHeader(header));
    	}
    }

    private void writeStructureHeader(Table table, com.licq.ldoc.domain.Element element) 
    	throws DocumentException {
    	Cell header = LowAgieUtils.createTableHeader(
    			new StringBuffer("Table. DTO ")
    				.append(element.getName())
    				.append(" Elements and Attributes")
    				.toString()
    	);
    	header.setColspan(TABLE_HEADERS.length);
    	table.addCell(header);
    }

}
